#include "spi1.h"

#define READ_STATUS 0x8001      //8000
#define READ_ANGLE_VALUE 0x8021 //8020
#define READ_SPEED_VALUE 0x8031 //8030
#define SPI_TX_OFF {GPIOA->CRL&=0x0FFFFFFF;GPIOA->CRL|=0x40000000;}//把PA7（MOSI）配置成开漏--输入模式
#define SPI_TX_ON  {GPIOA->CRL&=0x0FFFFFFF;GPIOA->CRL|=0xB0000000;}//把PA7（MOSI）配置成推挽--输出模式（50MHz）
 
void SPI1_Init(void)
{
	SPI_InitTypeDef  SPI_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_APB2PeriphClockCmd( RCC_APB2Periph_SPI1,ENABLE );
 
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //PA5--CLK--复用推挽
	GPIO_Init(GPIOA,&GPIO_InitStructure);
 
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;   //PA6--MISO--输入
	GPIO_Init(GPIOA,&GPIO_InitStructure);
 
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//PA7--MOSI--推挽输出
	GPIO_Init(GPIOA,&GPIO_InitStructure);
 
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;       //PA4--CS--推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
 
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//SPI1--双线全双工！！
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStructure.SPI_CRCPolynomial = 7;
	SPI_Init(SPI1,&SPI_InitStructure);
	SPI_Cmd(SPI1,ENABLE);
}
 
//SPIx 读写一个字节
//TxData:要写入的字节
//返回值:读取到的字节
u16 SPI1_ReadWriteByte(u16 TxData)
{
	u8 retry=0;
	while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET) 
		{ //检查指定的SPI标志位设置与否:发送缓存空标志位
		retry ++;
		if(retry>200)
			return 0;
	}
	SPI_I2S_SendData(SPI1, TxData); //通过外设SPIx发送一个数据
	retry=0;
 
	while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET) 
		{ //检查指定的SPI标志位设置与否:接受缓存非空标志位
		retry ++;
		if(retry>200)
			return 0;
	}
	return SPI_I2S_ReceiveData(SPI1); //返回通过SPIx最近接收的数据
}
 
uint16_t ReadValue(uint16_t u16RegValue)
{
	uint16_t u16Data;
 
	SPI_CS_ENABLE;
	SPI1_ReadWriteByte(u16RegValue);
	SPI_TX_OFF;
 
	u16Data = ( SPI1_ReadWriteByte(0xffff) & 0x7FFF ) << 1;//0x12/0xff*100k
	SPI_CS_DISABLE;
	SPI_TX_ON;
	return(u16Data);
}
 
//得到 0~359 度
uint16_t ReadAngle(void)
{
    return ( ReadValue(READ_ANGLE_VALUE) * 360 / 0x10000 );
}
